<?php

	// +----------------------------------------------------------------------
	// | 在线云服务
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2022 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace yicmf\cloud;

	use think\facade\Cache;
	use think\Exception;
	use think\Container;
	use think\facade\Db;
	use yicmf\tools\HttpService;

	class Server
	{
		// 需要发送的数据
		private $data = [];
		private $action;
		private $app;
		/**
		 * Request实例
		 * @var \think\Request
		 */
		protected $request;
		private $domain = 'https://cloud.yicmf.com/api/cloud/';

		/**
		 * 是否正常运行
		 * @var bool
		 */
		private $is_running = true;

		public function __construct()
		{
			$this->app = app();
			$this->request = app('request');
			$langSet = $this->app->lang->getLangSet();
			$lang_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $langSet . '.php';
			is_file($lang_file) && $this->app->lang->load($lang_file);
			if (!Cache::has('open_cloud')) {
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_HEADER, 1);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
				curl_setopt($ch, CURLOPT_URL, $this->domain. 'foreign/connect');
				curl_exec($ch);
				$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				curl_close($ch);
				Cache::set('open_cloud', $httpcode, 3600 * 24);
			} else {
				$httpcode = Cache::get('open_cloud');
			}
			if (200 != $httpcode) {
				$this->is_running = false;
			}
		}

		/**
		 * 需要发送的数据.
		 * @param $data
		 * @return $this
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function data($data)
		{
			$this->data = $data;
			return $this;
		}

		/**
		 * 执行对应命令.
		 * @param string $action 例如 version.detection
		 * @return array
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function action($action)
		{
			if ($this->is_running) {
				if (empty($this->data)) {
					$data = null;
				} else {
					$data = $this->data;
					// 重置，以便下一次服务请求
					$this->data = null;
				}
				$this->action = str_replace('.', '/', $action);;
				return $this->run($data);
			} else {
				return ['code' => 1, 'message' => lang('cloud is close!')];
			}
		}


		/**
		 * 请求
		 * @param array $param
		 * @return array
		 */
		private function run($param = [])
		{
			$params = [
				'data' => base64_encode(json_encode($param)),
				'identity' => $this->getIdentity(),
				'signType' => 'base64',
				'format' => 'json',
			];
			try {
				$headers = [
					'Content-Type' => 'application/x-www-form-urlencoded',
					'cloud-token' => think_encrypt(md5($params['data'] . $params['identity']), 'yicmf'),
				];
				$result = HttpService::request($this->domain . $this->action, $params, 'POST', $headers);
				if (!isset($result['content'])) {
					throw new Exception($result['message'], $result['code']);
				}
				$result = $result['content'];
			} catch (Exception $e) {
				$result['code'] = $e->getCode();
				$result['message'] = $e->getMessage();
			}
			return $result;
		}


		/**
		 * 会员帐号信息.
		 * @return string
		 */
		private function getIdentity()
		{
			if ('cli' == PHP_SAPI) {
				$host = config('setting.host');
				$ip = '';
			} else {
				$host = $this->request->host(true);
				$ip = $this->request->ip();
			}
			$dentity = [
				'name' => config('setting.name'),
				'version' => config('setting.version'),
				'edition' => config('setting.edition'),
				'build' => config('setting.build'),
				'web_uuid' => config('ucenter.web_uuid'),
				'app_id' => config('setting.app_id'),
				'app_key' => config('setting.app_key'),
				'lang' => $this->app->lang->defaultLangSet(),
				'user_agent' => $this->request->header('user-agent'),
				'domain' => $host,
				'admin_email' => $this->request->user?$this->request->user['email']:'',
				'admin_mobile' => $this->request->user?$this->request->user['mobile']:'',
				'user' => Db::name('user')->count(),
				'user_login' => Db::name('user')->sum('login_count'),
				'sapi' => PHP_SAPI,
				'ip' => $ip
			];
			return base64_encode(json_encode($dentity));
		}
	}